package com.xzy.mybatis.cipher.spring;

import com.xzy.mybatis.cipher.plugin.DecryptPlugin;
import com.xzy.mybatis.cipher.plugin.EncryptPlugin;
import com.xzy.mybatis.cipher.support.DatasourceHolder;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author xzy.xiao
 * @since 2025/1/14  19:06
 */
@Slf4j
public class MybatisCipherInitializingBean implements InitializingBean {

    @Autowired
    private DatasourceHolder datasourceHolder;
    @Autowired
    private List<SqlSessionFactory> sqlSessionFactoryList;

    @Setter
    private MybatisCipherContext mybatisCipherContext;

    @Override
    public void afterPropertiesSet() {
        for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
            Configuration configuration = sqlSessionFactory.getConfiguration();
            configuration.addInterceptor(new EncryptPlugin(datasourceHolder, mybatisCipherContext));
            configuration.addInterceptor(new DecryptPlugin(datasourceHolder, mybatisCipherContext));
            log.debug("Add `EncryptPlugin` and `DecryptPlugin` into `SqlSessionFactory`: {} ", sqlSessionFactory);
        }
    }
}
